﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraSplashScreen;
using Fcdbas.WinUI.Forms;
using Fcdbas.WinUI.Controls;
using Fcdbas.Platform.Properties;
using Fcdbas.Platform.Enums;
using Fcdbas.Core.Windows;
using Fcdbas.WinUI.Design;
using Fcdbas.Platform;
using Fcdbas.WinUI.Windows;
using Fcdbas.WinUI.Common;
using Fcdbas.Core.Compression;
using Fcdbas.Core;
namespace Fcdbas.WinUI.Forms
{
    public partial class cMasterDetailWindow : BaseForm
    {
        public cMasterDetailWindow()
        {
            InitializeComponent();
            WindowActions += new WindowActionsEventHandler(cMasterDetailWindow_WindowActions);
        }

        void cMasterDetailWindow_WindowActions(object sender, WindowActionsEventArgs e)
        {
            switch (e.ActionType)
            {
                case Const.PM_DataRecordRefresh:
                    DataSourceBinding dsb = e.WParam as DataSourceBinding;
                    RefreshDetail(dsb,e.LParam);
                    ClearGridEmptyRow();
                    break;
                
            }
        }
        #region 私有方法
        /// <summary>
        /// 刷新所有了表的数据
        /// </summary>
        /// <param name="parentNo"></param>
        //private void RefreshDetail(object parents)
        //{
        //    Dictionary<string, object> keys = parents as Dictionary<string, object>;

        //    if (this.MasterdataSourceBinding.Details != null)
        //    {
                
        //            foreach (DataSourceBinding dsb in this.MasterdataSourceBinding.Details)
        //            {
        //                if (keys.Count > 0)
        //                {
        //                dsb.UserWhere = "";
        //                string where = "";
        //                if (dsb.Columns != null)
        //                {
        //                    foreach (DataItem di in dsb.Columns)
        //                    {
        //                        if (di.Flags == DataItemFlags.ParentKey)
        //                        {
        //                            foreach (string parent in keys.Keys)
        //                            {
        //                                if (di.ColumnName.ToLower() == parent.ToLower())
        //                                {
        //                                    if (string.IsNullOrEmpty(where))
        //                                        where = di.ColumnName + " = '" + keys[parent].ToString() + "'";
        //                                    else
        //                                        where = where + " and " + di.ColumnName + " = '" + keys[parent].ToString() + "'";
        //                                }
        //                            }

        //                        }
        //                    }
        //                }
        //                dsb.ParentWhere = where;
        //                //if (string.IsNullOrEmpty(dsb.DefaultWhere))
        //                //{
        //                //    dsb.DefaultWhere = where;
        //                //    dsb.ParentWhere = where;
        //                //}
        //                //else
        //                //{
        //                //    if (dsb.DefaultWhere == dsb.ParentWhere)
        //                //    {
        //                //        dsb.DefaultWhere = where;
        //                //        dsb.ParentWhere = dsb.DefaultWhere;
        //                //    }
        //                //    else
        //                //    {
        //                //        if (!string.IsNullOrEmpty(dsb.ParentWhere))
        //                //        {
        //                //            dsb.DefaultWhere.Replace(dsb.ParentWhere, "");
        //                //            dsb.ParentWhere = "";
        //                //        }
        //                //        dsb.ParentWhere = " and " + where;
        //                //        dsb.DefaultWhere = dsb.DefaultWhere + dsb.ParentWhere;
        //                //    }
        //                //}
        //                //dsb.OldEntity = null;
        //                dsb.OldEntitys.Clear();

        //                if (IsAutoPopulate)
        //                {
        //                    dsb.vrtDataSourceRefresh(DataSourcePopulate.All);
                            
        //                }
                       
        //                //if (dsb.Session.RecordCount > cSessionManager.RecordLimit)
        //                //{
        //                //    dlgAskFetch dlgFetch = new dlgAskFetch(dsb.Session.RecordCount);
        //                //    if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
        //                //    {
        //                //        dsb.vrtDataSourceRefresh(dlgFetch.FetchMode);
        //                //    }
        //                //}
        //            }
        //            else
        //            {
        //                dsb.OldEntitys.Clear();
        //                dsb.List.Clear();
        //            }
        //            dsb.ResetBindings(false);
                    
        //            SetControlReadOnly(this, dsb);
                    
        //        }
        //    }
        //    SplashScreenManager.CloseForm(false);
        //}
        private void RefreshDetail(DataSourceBinding currentDSB, object parents)
        {
            if (currentDSB == null)
            {
                SplashScreenManager.CloseForm(false);
                return;
            }
            int nCount = 0;
            Dictionary<string, object> keys = parents as Dictionary<string, object>;

            if (currentDSB.Details != null)
            {
                foreach (DataSourceBinding dsb in currentDSB.Details)
                {
                    if (keys.Count > 0)
                    {
                        dsb.UserWhere = "";
                        string where = "";
                        if (dsb.Columns != null)
                        {
                            foreach (DataItem di in dsb.Columns)
                            {
                                if (di.Flags == DataItemFlags.ParentKey)
                                {
                                    foreach (string parent in keys.Keys)
                                    {
                                        if (di.ColumnName.ToLower() == parent.ToLower())
                                        {
                                            if (string.IsNullOrEmpty(where))
                                                where = di.ColumnName + " = '" + keys[parent].ToString() + "'";
                                            else
                                                where = where + " and " + di.ColumnName + " = '" + keys[parent].ToString() + "'";
                                        }
                                    }

                                }
                            }
                        }
                        dsb.ParentWhere = where;

                        dsb.OldEntitys.Clear();
                        if (IsAutoPopulate)
                        {
                            if (cSessionManager.IsRemote)
                            {
                                dsb.PrepareQuery();
                                nCount++;
                            }
                            else
                                dsb.vrtDataSourceRefresh(DataSourcePopulate.All);
                        }
                    }
                    else
                    {
                        dsb.OldEntitys.Clear();
                        dsb.List.Clear();
                    }
                    if (!cSessionManager.IsRemote)
                    {
                        dsb.ResetBindings(false);

                        SetControlReadOnly(this, dsb);
                    }

                }
                if (cSessionManager.IsRemote && nCount > 0)
                {
                    Fcdbas.DataContract.QuaryResult result = cSessionManager.BatchQuery();
                    if (!result.Success)
                    {
                        this.Error(result.Message);
                    }
                    else
                    {
                        if (result.ResultList != null)
                        {
                            foreach (DataContract.ObjectResult obj in result.ResultList)
                            {
                                IEntityList list = null;
                                if (obj.IsCompress && obj.Data != null)
                                {
                                    byte[] data = obj.Data.Decompress();
                                    list = Fcdbas.Core.Util.ObjectHelper.DeserialzieObject(data) as IEntityList;
                                }
                                else
                                    list = obj.EntityList;
                                DataSourceBinding dsb = currentDSB.Details.Find(p => p.Name == obj.DataSourceName);
                                if (dsb != null)
                                    dsb.BindFromDatasource(list);
                            }
                        }
                    }
                }
            }
            //if(IsAutoPopulate)
            //    SplashScreenManager.CloseForm(false);
        }
        
        protected override void InitBind()
        {
            if (!string.IsNullOrEmpty(MasterdataSourceBinding.ViewName))
            {
                AddDSProcedure(this.MasterdataSourceBinding.PackageName, MasterdataSourceBinding.Updates);
                AddDSSecurity(this.MasterdataSourceBinding.ViewName, SecObjectType.View, "*", MasterdataSourceBinding.Updates);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".New", SecObjectType.DataSource, "新增", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Modify", SecObjectType.DataSource, "修改", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Query", SecObjectType.DataSource, "查询", UpdatesSql.Standard);
                AddUserFunction(this.MasterdataSourceBinding.Name + ".Delete", SecObjectType.DataSource, "删除", UpdatesSql.Standard);
            }
            this.MasterdataSourceBinding.IsUserNew = this.IsDataSourceNew(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserModify = this.IsDataSourceModify(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserDelete = this.IsDataSourceDelete(this.MasterdataSourceBinding.Name);
            this.MasterdataSourceBinding.IsUserQuery = this.IsDataSourceQuery(this.MasterdataSourceBinding.Name);
            SuspendBinding(this.MasterdataSourceBinding);
            if (ChildContainer == null && UIDebug)
            {
                this.ShowMessage("VS设计器出错，Container 对象为空，请增加一个一个BindingSource，VS会自动修复");
                return;
            }
            if (ChildContainer != null)
            {
                for (int i = 0; i < ChildContainer.Components.Count; i++)
                {
                    if (ChildContainer.Components[i] is DataSourceBinding)
                    {
                        DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                        dataSourceBinding.InitDataSource();
                        dataSourceBinding.FetchRowsDone += new EventHandler<cDataSource.ReturnEventArgsSalNumber>(MasterdataSourceBinding_FetchRowsDone);
                        SuspendBinding(dataSourceBinding);
                        if (string.IsNullOrEmpty(dataSourceBinding.ViewName))
                            continue;
                        if (!string.IsNullOrEmpty(dataSourceBinding.ViewName))
                        {
                            AddDSProcedure(dataSourceBinding.PackageName, dataSourceBinding.Updates);
                            AddDSSecurity(dataSourceBinding.ViewName, SecObjectType.View, "*", dataSourceBinding.Updates);
                            AddUserFunction(dataSourceBinding.Name + ".New", SecObjectType.DataSource, "新增", UpdatesSql.Standard);
                            AddUserFunction(dataSourceBinding.Name + ".Modify", SecObjectType.DataSource, "修改", UpdatesSql.Standard);
                            AddUserFunction(dataSourceBinding.Name + ".Query", SecObjectType.DataSource, "查询", UpdatesSql.Standard);
                            AddUserFunction(dataSourceBinding.Name + ".Delete", SecObjectType.DataSource, "删除", UpdatesSql.Standard);
                        }
                        dataSourceBinding.IsUserNew = this.IsDataSourceNew(dataSourceBinding.Name);
                        dataSourceBinding.IsUserModify = this.IsDataSourceModify(dataSourceBinding.Name);
                        dataSourceBinding.IsUserDelete = this.IsDataSourceDelete(dataSourceBinding.Name);
                        dataSourceBinding.IsUserQuery = this.IsDataSourceQuery(dataSourceBinding.Name);
                        m_salWindow.AddWindowActions(dataSourceBinding);
                        dataSourceBinding.Session.DataSourceSaveCompleted += new EventHandler(Session_DataSourceSaveCompleted);
                        dataSourceBinding.Session.DataSourceDeleted += new cDataSource.DataRecordDeletedEventHandler(Session_DataSourceDeleted);
                        //if (ViewAuthorized(dataSourceBinding.View))
                        {
                            if ((HasChildItem(this.MasterdataSourceBinding, dataSourceBinding) && dataSourceBinding.LogicalParent == null) || (dataSourceBinding.LogicalParent != null && dataSourceBinding.LogicalParent.Equals(this.MasterdataSourceBinding)))
                            {
                                dataSourceBinding.LogicalParent = MasterdataSourceBinding;
                                MasterdataSourceBinding.Details.Add(dataSourceBinding);
                                dataSourceBinding.CurrentChanged += new EventHandler(this.MasterdataSourceBinding_CurrentChanged);
                                continue;
                            }
                            // SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 1, dataSourceBinding.Session.GetHashCode());


                        }
                    }
                }
                for (int i = 0; i < ChildContainer.Components.Count; i++)
                {
                    if (ChildContainer.Components[i] is DataSourceBinding)
                    {
                        DataSourceBinding dataSourceBinding = ChildContainer.Components[i] as DataSourceBinding;
                        if (string.IsNullOrEmpty(dataSourceBinding.ViewName))
                            continue;
                        for (int j = 0; j < ChildContainer.Components.Count; j++)
                        {
                            if (ChildContainer.Components[j] is DataSourceBinding)
                            {
                                DataSourceBinding dataSourceBinding1 = ChildContainer.Components[j] as DataSourceBinding;
                                if (dataSourceBinding1.LogicalParent != null && dataSourceBinding1.LogicalParent.Equals(dataSourceBinding))
                                {
                                    dataSourceBinding.Details.Add(dataSourceBinding1);
                                }
                            }
                        }
                        ///如果存在刷新数据,注释掉，不自动读取数据
                        /*
                        if (dataSourceBinding.Details.Count > 0)
                        {
                            if (IsDataSourceQuery(dataSourceBinding.Name))
                            {
                                SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 3, dataSourceBinding.Identify);
                                if (dataSourceBinding.LogicalParent == null && dataSourceBinding.IsLimit && dataSourceBinding.Session.RecordCount > dataSourceBinding.RecordLimit)
                                {
                                    dlgAskFetch dlgFetch = new dlgAskFetch(dataSourceBinding.Session.RecordCount, dataSourceBinding, this);
                                    if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                                    {
                                        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, dataSourceBinding.Identify);
                                    }
                                }
                                else
                                    SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, dataSourceBinding.Identify);
                            }
                        }
                        else if (dataSourceBinding.LogicalParent == null && !string.IsNullOrEmpty(dataSourceBinding.ViewName))//单独的datasource
                        {
                            if (IsDataSourceQuery(dataSourceBinding.Name) && IsAutoPopulate)
                                SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, dataSourceBinding.Identify);
                        }
                         * */
                    }

                }
            }
            RefreshMasterData();
            //if (IsDataSourceQuery(this.MasterdataSourceBinding.Name))
            //{
            //    SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 3, MasterdataSourceBinding.Identify);
            //    if (this.MasterdataSourceBinding.LogicalParent == null && this.MasterdataSourceBinding.IsLimit && this.MasterdataSourceBinding.Session.RecordCount > this.MasterdataSourceBinding.RecordLimit)
            //    {
            //        dlgAskFetch dlgFetch = new dlgAskFetch(this.MasterdataSourceBinding.Session.RecordCount, this.MasterdataSourceBinding, this);
            //        if (dlgFetch.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            //        {
            //            SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, dlgFetch.FetchMode, this.MasterdataSourceBinding.Identify);
            //        }
            //    }
            //    else
            //        SalWindow.FireWindowActions(this, Const.PM_DataSourceRefresh, 2, this.MasterdataSourceBinding.Identify);
            //}
            //SetControlReadOnly(this, MasterdataSourceBinding);
           // BindRelBoxValue();
        }

       

        protected bool HasChildItem(DataSourceBinding parentBinding, DataSourceBinding childBinding)
        {
           

            foreach (DataItem dataItem in childBinding.Columns)
            {
                
                    if (dataItem.Flags == DataItemFlags.ParentKey)
                    {
                        if (parentBinding.Columns.Find(p => p.ColumnName ==dataItem.ColumnName) != null)
                            return true;
                    }
                
            }

            return false;
        }

       

        #endregion

    }
}
